import { v4 as uuidv4 } from 'uuid';

class ConversationNode {
  constructor(message, role, parent = null, files = []) {
    this.id = uuidv4();
    this.message = message;
    this.role = role;  // 'user' 或 'assistant'
    this.parent = parent;
    this.children = [];
    this.timestamp = Date.now();
    this.files = files;  // 存储文件信息，包括图片

    if (parent) {
      parent.children.push(this);
    }
  }

  toDict() {
    return {
      id: this.id,
      message: this.message,
      role: this.role,
      timestamp: this.timestamp,
      childrenIds: this.children.map(child => child.id),
      files: this.files
    };
  }
}

class ConversationManager {
  constructor() {
    this.root = null;
    this.currentPath = [];
    this.currentNode = null;
    this.branches = [];
    this.nodes = {};  // 用于快速查找节点

    // 创建初始分支
    const initialBranch = {
      id: 'initial',
      name: '主线对话',
      currentNode: null,
      color: '#0066cc'
    };
    this.branches.push(initialBranch);
    
    // 添加初始对话数据
    this._addInitialMessages();
  }
  
  _addInitialMessages() {
    // 添加一些示例对话数据
    this.addMessage('1+1=?', 'user');
    this.addMessage('2', 'assistant');
    this.addMessage('再乘以14', 'user');
    this.addMessage('28', 'assistant');
    
    // 确保初始消息被正确添加到当前路径和分支
    if (this.branches.length > 0 && this.currentNode) {
      this.branches[0].currentNode = this.currentNode;
    }
    
    // 确保currentPath包含所有初始消息
    if (this.currentPath.length === 0 && this.root) {
      this.currentPath = [];
      let node = this.root;
      while (node) {
        this.currentPath.push(node);
        if (node.children.length > 0) {
          node = node.children[0]; // 只取第一个子节点，这是简单的线性对话路径
        } else {
          break;
        }
      }
      this.currentNode = this.currentPath[this.currentPath.length - 1];
    }
  }

  addMessage(message, role, files = []) {
    const newNode = new ConversationNode(message, role, this.currentNode, files);

    if (!this.root) {
      this.root = newNode;
    }

    this.nodes[newNode.id] = newNode;
    this.currentPath.push(newNode);
    this.currentNode = newNode;

    // 更新当前分支信息
    // 查找当前分支并更新其currentNode或currentNodeId
    if (this.currentNode.parent) { // 确保父节点存在
      for (const branch of this.branches) {
        // 检查分支的currentNode是否等于当前节点的父节点
        const isMatchCurrentNode = branch.currentNode && branch.currentNode.id === this.currentNode.parent.id;
        // 检查分支的currentNodeId是否等于当前节点的父节点ID
        const isMatchCurrentNodeId = branch.currentNodeId === this.currentNode.parent.id;
        
        if (isMatchCurrentNode || isMatchCurrentNodeId) {
          // 保持数据结构一致性，只更新对应的属性
          if ('currentNodeId' in branch) {
            branch.currentNodeId = newNode.id;
          } else {
            branch.currentNode = newNode;
          }
          // 不需要break，因为可能有多个分支需要更新（虽然这种情况很少见）
        }
      }
    }

    return newNode;
  }

  createBranch(nodeId) {
    if (!this.nodes[nodeId]) {
      throw new Error(`节点ID ${nodeId} 不存在`);
    }

    const targetNode = this.nodes[nodeId];
    const branchId = uuidv4();
    
    // 尝试获取问题作为分支名称
    let branchName = this._getQuestionForBranch(targetNode);
    if (!branchName || branchName.trim() === '') {
      branchName = `分支 ${this.branches.length}`;
    }

    // 生成随机颜色
    const colors = ['#0066cc', '#4CAF50', '#FF9800', '#E91E63', '#9C27B0', '#00BCD4', '#FF5722'];
    const color = colors[this.branches.length % colors.length];

    const newBranch = {
      id: branchId,
      name: branchName,
      currentNodeId: nodeId, // 使用节点ID而不是直接引用节点对象
      color: color
    };

    // 添加新分支并重新创建数组引用，触发Vue的响应式更新
    this.branches.push(newBranch);
    // 创建新的数组引用
    this.branches = [...this.branches];
    this.switchBranch(branchId);

    return branchId;
  }

  switchBranch(branchId) {
    const targetBranch = this.branches.find(branch => branch.id === branchId);
    
    if (!targetBranch) {
      throw new Error(`分支ID ${branchId} 不存在`);
    }

    // 修复：根据currentNodeId获取实际节点，兼容currentNode属性
    if (targetBranch.currentNodeId) {
      this.currentNode = this.nodes[targetBranch.currentNodeId];
    } else if (targetBranch.currentNode) {
      this.currentNode = targetBranch.currentNode;
    } else {
      throw new Error('分支没有设置当前节点');
    }

    // 重新构建当前路径
    this.currentPath = [];
    let node = this.currentNode;
    while (node) {
      this.currentPath.push(node);
      node = node.parent;
    }
    
    // 反转路径，使其从根节点开始
    this.currentPath.reverse();
  }

  /**
   * 从目标节点获取对应的问题文本作为分支名称
   * @param {ConversationNode} targetNode - 创建分支的目标节点
   * @returns {string} - 分支名称
   */
  _getQuestionForBranch(targetNode) {
    // 如果目标节点本身就是用户消息，直接使用其内容
    if (targetNode.role === 'user') {
      return this._truncateText(targetNode.message, 50);
    }
    
    // 如果目标节点是AI回复，尝试获取对应的用户问题
    // 向前查找最近的用户消息节点
    let current = targetNode.parent;
    while (current) {
      if (current.role === 'user') {
        return this._truncateText(current.message, 50);
      }
      current = current.parent;
    }
    
    return null;
  }
  
  /**
   * 截断文本到指定长度，如果超过长度则添加省略号
   * @param {string} text - 要截断的文本
   * @param {number} maxLength - 最大长度
   * @returns {string} - 截断后的文本
   */
  _truncateText(text, maxLength) {
    if (text && text.length > maxLength) {
      return text.substring(0, maxLength) + '...';
    }
    return text;
  }

  getContextForNode(node) {
    const path = [];
    let current = node;
    while (current) {
      path.push(current);
      current = current.parent;
    }

    path.reverse();

    return path.map(n => ({
      role: n.role,
      content: n.message
    }));
  }

  getCurrentContext() {
    if (!this.currentNode) {
      return [];
    }
    return this.getContextForNode(this.currentNode);
  }

  getBranchById(branchId) {
    return this.branches.find(branch => branch.id === branchId) || null;
  }

  renameBranch(branchId, newName) {
    const branch = this.getBranchById(branchId);
    if (branch) {
      branch.name = newName;
    }
  }

  deleteBranch(branchId) {
    if (this.branches.length <= 1) {
      throw new Error("不能删除最后一个分支");
    }

    const index = this.branches.findIndex(branch => branch.id === branchId);
    if (index !== -1) {
      const branchToDelete = this.branches[index];
      
      // 如果删除的是当前分支，切换到第一个分支
      if (branchToDelete.currentNode === this.currentNode) {
        this.switchBranch(this.branches[0].id);
      }

      this.branches.splice(index, 1);
    }
  }

  // 返回一个不包含循环引用的分支信息数组
  getAllBranches() {
    // 创建新的分支信息数组，只包含UI渲染所需的信息
    return this.branches.map(branch => ({
      id: branch.id,
      name: branch.name,
      color: branch.color,
      // 不直接引用节点对象，而是使用节点ID来标识
      currentNodeId: branch.currentNode ? branch.currentNode.id : null
    }));
  }

  isNodeInBranch(node, branchRoot) {
    if (!node || !branchRoot) {
      return false;
    }

    if (node.id === branchRoot.id) {
      return true;
    }

    let current = node.parent;
    while (current) {
      if (current.id === branchRoot.id) {
        return true;
      }
      current = current.parent;
    }

    return false;
  }

  getNodeById(nodeId) {
    return this.nodes[nodeId];
  }

  getNodeContextSummary(nodeId) {
    const node = this.getNodeById(nodeId);
    if (!node) {
      return "";
    }

    let parent = node.parent;
    if (parent && parent.role === 'user') {
      return parent.message.length > 50 ? parent.message.substring(0, 50) + '...' : parent.message;
    }

    let current = parent;
    while (current) {
      if (current.role === 'user') {
        return current.message.length > 50 ? current.message.substring(0, 50) + '...' : current.message;
      }
      current = current.parent;
    }

    return "";
  }
}

// 创建一个单例实例
export const conversationManager = new ConversationManager();